package com.ngkj.zmfptwebsocket.chatModule.service.read.imp;

import com.ngkj.zmfptCommon.common.bean.ChatMessage;
import com.ngkj.zmfptwebsocket.chatModule.mapper.read.ChatReadMapper;
import com.ngkj.zmfptwebsocket.chatModule.service.read.ChatReadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author ChenHN
 * @since 2021/11/29 creation
 **/
@Slf4j
@Service
public class ChatReadServiceImpl implements ChatReadService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ChatReadMapper chatReadMapper;


    @Override
    public List<ChatMessage> getTalkingMessage(String userId,String toUserId) {
        String cacheName = catchCacheName(userId, toUserId);
        List<ChatMessage> chatMessageList = redisTemplate.opsForList().range(cacheName, 0, -1);
        if (chatMessageList.size()==0) {
            List<ChatMessage> talkingMessage = chatReadMapper.getTalkingMessage(userId, toUserId);
            if (talkingMessage.size()==0){
                return new ArrayList<>();
            }
            redisTemplate.opsForList().leftPushAll(cacheName,talkingMessage);
            Collections.reverse(talkingMessage);
            return talkingMessage;
        }
        return chatMessageList;
    }

    @Override
    public List<ChatMessage> addTalkingMessage(String userId, String toUserId) {
        String cacheName = catchCacheName(userId, toUserId);
        ChatMessage chatMessage = (ChatMessage) redisTemplate.opsForList().index(cacheName, 0);
        String sendTime = chatMessage.getSendTime();
        List<ChatMessage> chatMessageList = chatReadMapper.addTalkingMessage(sendTime, userId, toUserId);
        if (chatMessageList.size()==0){
            return new ArrayList<>();
        }
        redisTemplate.opsForList().leftPushAll(cacheName,chatMessageList);
        Collections.reverse(chatMessageList);
        return chatMessageList;
    }

    @Override
    public List<Map<String, Object>> getMessageList(Long userId) {
        return chatReadMapper.getMessageList(userId);
    }

    private String catchCacheName(String userId, String toUserId) {
        int userInt = Integer.parseInt(userId);
        int toUserInt = Integer.parseInt(toUserId);
        String cacheName = null;
        if (userInt<toUserInt){
            cacheName = "websocket_show " + userId + "-" + toUserId;
        }else{
            cacheName = "websocket_show " + toUserId + "-" + userId;
        }
        return cacheName;
    }

}
